package com.lancoo.ccas53.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.ccas53.config.LancooConfig;
import com.lancoo.ccas53.entity.*;
import com.lancoo.ccas53.exception.BizException;
import com.lancoo.ccas53.mapper.CourseMapper;
import com.lancoo.ccas53.pojo.common.PageInfo;
import com.lancoo.ccas53.pojo.dto.CourseDto;
import com.lancoo.ccas53.pojo.dto.SetCourseDto;
import com.lancoo.ccas53.pojo.dto.TeachingClassWeekListDto;
import com.lancoo.ccas53.pojo.excel.ExcelPreSelectCourseLog;
import com.lancoo.ccas53.pojo.response.BasicPlatformResponse;
import com.lancoo.ccas53.pojo.response.basicPlatform.BaseCourse;
import com.lancoo.ccas53.pojo.response.basicPlatform.BaseLink;
import com.lancoo.ccas53.pojo.vo.CourseInput;
import com.lancoo.ccas53.pojo.vo.CourseParameterSetVo;
import com.lancoo.ccas53.pojo.vo.CourseTreeVo;
import com.lancoo.ccas53.service.*;
import com.lancoo.ccas53.util.MyExcelUtils;
import com.lancoo.ccas53.util.PagingUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程环节表 服务实现类
 * </p>
 *
 * @author quin.song
 * @since 2024-05-20
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Resource
    private CourseMapper courseMapper;
    @Resource
    @Lazy
    private YunBasicService yunBasicService;
    @Resource
    @Lazy
    private YunBasicServiceImpl yunBasicServiceImpl;
    @Resource
    private CourseWeekService courseWeekService;
    @Resource
    private TeachingClassService teachingClassService;
    @Resource
    private TeachingClassWeekService teachingClassWeekService;
    @Resource
    private TeachingClassTeacherService teachingClassTeacherService;
    @Resource
    private TeacherCourseService teacherCourseService;
    @Resource
    private PlanTeachingCourseService planTeachingCourseService;
    @Resource
    private PlanTeachingService planTeachingService;
    @Resource
    private MajorGradeService majorGradeService;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private StudentService studentService;
    @Resource
    private TeachingClassStudentService teachingClassStudentService;
    @Resource
    private CssPreSelectStudentService cssPreSelectStudentService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private PlanTeachingStudentService planTeachingStudentService;
    @Resource
    private CourseService courseService;
    @Resource
    private LancooConfig lancooConfig;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncBaseCourse(Integer taskId, String schoolId) {
        Set<Course> courses = new HashSet<>();
        List<BaseCourse> baseCourses = yunBasicService.getBaseCourse(schoolId);
        List<BaseLink> baseSegments = yunBasicService.getBaseSegment(schoolId);
        for (BaseCourse baseCourse : baseCourses) {
            courses.add(baseCourse.toCourse(taskId));
        }
        for (BaseLink baseSegment : baseSegments) {
            courses.add(baseSegment.toCourse(taskId));
        }
        this.syncCourse(taskId, courses);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncCourse(Integer taskId, Set<Course> courses) {
        List<Course> insertList = new ArrayList<>();
        List<Course> courseList = courseMapper.getcourseList(taskId);
        List<String> baseIds = courseList.stream().map(Course::getBaseCourseId).collect(Collectors.toList());
        for (Course course : courses) {
            if (!baseIds.contains(course.getBaseCourseId())) {
                insertList.add(course);
            }
        }
        courseList.removeAll(courses);
        List<Long> deleteIds = courseList.stream().map(Course::getCourseId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(deleteIds)) {
            this.removeBatchByIds(deleteIds);
            courseWeekService.lambdaUpdate().in(CourseWeek::getCourseId, deleteIds).remove();
        }
        if (CollUtil.isNotEmpty(insertList)) {
            this.saveBatch(insertList);
        }
        this.initCourseWeek(insertList, taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncPlanCourse(Integer taskId, Set<Course> courses) {
        List<Course> insertList = new ArrayList<>();
        List<Course> courseList = this.list(new LambdaQueryWrapper<Course>().eq(Course::getTaskId, taskId));
        List<String> baseIds = courseList.stream().map(Course::getBaseCourseId).collect(Collectors.toList());
        for (Course course : courses) {
            if (!baseIds.contains(course.getBaseCourseId())) {
                insertList.add(course);
            }
        }
        if (CollUtil.isNotEmpty(insertList)) {
            this.saveBatch(insertList);
        }
        this.initCourseWeek(insertList, taskId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void initCourseWeek(List<Course> courses, Integer taskId) {
        List<CourseWeek> weekList = new ArrayList<>();
        for (Course course : courses) {
            if (course.getComputerHour() != null && course.getComputerHour() != 0) {
                CourseWeek week = new CourseWeek()
                        .setTaskId(course.getTaskId())
                        .setCourseId(course.getCourseId())
                        .setHourType(3)
                        .setHourTypeName("上机")
                        .setTotalHour(course.getComputerHour());
                weekList.add(week);
            }
            if (course.getExperimentalHour() != null && course.getExperimentalHour() != 0) {
                CourseWeek week = new CourseWeek()
                        .setTaskId(course.getTaskId())
                        .setCourseId(course.getCourseId())
                        .setHourType(2)
                        .setHourTypeName("实验")
                        .setTotalHour(course.getExperimentalHour());
                weekList.add(week);
            }
            if (course.getOtherHour() != null && course.getOtherHour() != 0) {
                CourseWeek week = new CourseWeek()
                        .setTaskId(course.getTaskId())
                        .setCourseId(course.getCourseId())
                        .setHourType(4)
                        .setHourTypeName("其他")
                        .setTotalHour(course.getOtherHour());
                weekList.add(week);
            }
            if (course.getLectureHour() != null && course.getLectureHour() != 0) {
                CourseWeek week = new CourseWeek()
                        .setTaskId(course.getTaskId())
                        .setCourseId(course.getCourseId())
                        .setHourType(1)
                        .setHourTypeName("讲授")
                        .setTotalHour(course.getLectureHour());
                weekList.add(week);
            }
            if (weekList.stream().noneMatch(a -> a.getCourseId().equals(course.getCourseId()))) {
                CourseWeek week = new CourseWeek()
                        .setTaskId(course.getTaskId())
                        .setCourseId(course.getCourseId())
                        .setHourType(1)
                        .setHourTypeName("讲授")
                        .setTotalHour(1);
                weekList.add(week);
            }
        }
        courseWeekService.saveBatch(weekList);
    }

    @Override
    public List<Course> getCourseList(Integer taskId, String baseCollegeId, String courseTypeId, Integer courseNature, Integer flag, String keyword, Integer isSelect, Integer isEnable) {
        List<Course> courseByConditions = courseMapper.getCourseByConditions(taskId, baseCollegeId, courseTypeId, courseNature, flag, keyword, isSelect, isEnable);
        List<CourseWeek> courseWeeks = courseWeekService.lambdaQuery()
                .eq(CourseWeek::getTaskId, taskId).list();
        courseByConditions.forEach(course -> {
            List<CourseWeek> weekList = courseWeeks.stream()
                    .filter(p -> p.getCourseId().equals(course.getCourseId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(weekList)) {
                course.setCourseWeeks(weekList);
            } else {
                course.setCourseWeeks(new ArrayList<>());
            }
        });
        return courseByConditions;
    }

    @Override
    public SetCourseDto<Course> getCourseList(Page<Course> page, Integer taskId, Integer dataRange, String baseCollegeId, String courseTypeId, Integer courseNature, Integer flag, String keyword, Integer parameterSet) {
        List<Course> courseList = this.lambdaQuery().eq(Course::getTaskId, taskId)
                .eq(StrUtil.isNotBlank(baseCollegeId), Course::getBaseCollegeId, baseCollegeId)
                .eq(StrUtil.isNotBlank(courseTypeId), Course::getCourseTypeId, courseTypeId)
                .eq(ObjUtil.isNotNull(courseNature), Course::getCourseNature, courseNature)
                .eq(ObjUtil.isNotNull(flag), Course::getFlag, flag)
                .eq(ObjUtil.isNotNull(parameterSet), Course::getParameterSet, parameterSet)
                .like(StrUtil.isNotBlank(keyword), Course::getCourseName, keyword).list();
        //获取课程参数
        List<Long> courseIds = courseList.stream().map(Course::getCourseId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(courseIds)) {
            Map<Long, List<CourseWeek>> courseWeekMap = courseWeekService.lambdaQuery()
                    .in(CourseWeek::getCourseId, courseIds)
                    .list()
                    .stream().collect(Collectors.groupingBy(CourseWeek::getCourseId));
            for (Course course : courseList) {
                course.setCourseWeeks(courseWeekMap.getOrDefault(course.getCourseId(), new ArrayList<CourseWeek>()));
                course.setTotalHour(course.getLectureHour() + course.getExperimentalHour() + course.getComputerHour() + course.getOtherHour());
            }
        }

        SetCourseDto<Course> result = new SetCourseDto<>();
        //过滤没有课程参数的课程
        List<Course> emptyCouseList = courseList.stream()
                .filter(a -> CollUtil.isEmpty(a.getCourseWeeks()))
                .collect(Collectors.toList());
        courseList.removeAll(emptyCouseList);
        //筛选教学计划启用的课程
        List<String> planTeachingIds = planTeachingService.lambdaQuery()
                .eq(PlanTeaching::getTaskId, taskId)
                .eq(PlanTeaching::getIsEnable, 1)
                .list()
                .stream().map(PlanTeaching::getBaseTeachingPlanId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(planTeachingIds)) {
            List<String> baseCourseIds = planTeachingCourseService.lambdaQuery()
                    .eq(PlanTeachingCourse::getTaskId, taskId)
                    .in(PlanTeachingCourse::getBaseTeachingPlanId, planTeachingIds)
                    .list().stream().map(PlanTeachingCourse::getBaseCourseId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(baseCourseIds)) {
                courseList = courseList.stream().filter(a -> baseCourseIds.contains(a.getBaseCourseId())).collect(Collectors.toList());
            }
        } else {
            //如果没有开启的教学计划，那么课程就是空的
            courseList = new ArrayList<>();
        }
        //数据处理，统计已设置参数的课程数量和未设置参数的课程数量
        Map<Integer, Long> statusCount = courseList.stream().collect(Collectors.groupingBy(Course::getParameterSet, Collectors.counting()));
        Long setNum = statusCount.getOrDefault(1, 0L);
        Long unSetNum = statusCount.getOrDefault(0, 0L);
        result.setSetNum(setNum);
        result.setUnSetNum(unSetNum);
        result.setTotal(courseList.size());

        if (dataRange != null && dataRange == 1) {
            //1已设置
            courseList = courseList.stream().filter(a -> a.getParameterSet() == 1).collect(Collectors.toList());
        } else if (dataRange != null && dataRange == 2) {
            //2未设置
            courseList = courseList.stream().filter(a -> a.getParameterSet() == 0).collect(Collectors.toList());
        }
        PageInfo<Course> pages = PagingUtil.getPages((int) page.getCurrent(), (int) page.getSize(), courseList);
        result.setList(pages.getList());
        result.setPages(pages.getPages());

        result.setCurrentPage(pages.getCurrentPage());
        result.setPageSize(pages.getPageSize());
        return result;
    }

    @Override
    public Boolean setCourseParams(Integer taskId, CourseInput courseInput) {
        //更新考核方式 参数设置状态
        this.lambdaUpdate()
                .eq(Course::getCourseId, courseInput.getCourseId())
                .set(Course::getParameterSet, 1)
                .set(courseInput.getAssessmentId() != null, Course::getAssessmentId, courseInput.getAssessmentId())
                .set(StrUtil.isNotEmpty(courseInput.getAssessmentName()), Course::getAssessmentName, courseInput.getAssessmentName())
                .update();

        //修改课程考核方式时，同步修改教学班考核方式
        if (courseInput.getAssessmentId() != null){
            List<TeachingClass> teachingClassList = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getCourseId, courseInput.getCourseId()).list();
            if (CollUtil.isNotEmpty(teachingClassList)){
                for (TeachingClass item : teachingClassList) {
                    item.setAssessmentId(Long.valueOf(courseInput.getAssessmentId()));
                    item.setAssessmentName(courseInput.getAssessmentName());
                }
                teachingClassService.updateBatchById(teachingClassList);
            }
        }

        //更新课程参数设置
        if (CollUtil.isNotEmpty(courseInput.getCourseWeeks())) {
            courseWeekService.saveOrUpdateBatch(courseInput.getCourseWeeks());
        }
        if (courseInput.getAssessmentId() != null && courseInput.getAssessmentName() != null) {
            TaskInfo taskInfo = taskInfoService.getById(taskId);
            Course course = this.getById(courseInput.getCourseId());
            //同步基础平台课程考核方式
            //http://192.168.129.1:8033/showdoc/web/#/6?page_id=8590
            String path = "/BaseApi/UserMgr/TeachInfoMgr/setTermCourseExamInfo";
            Map<String, String> map = new HashMap<>();
            String strAppId = lancooConfig.getSysId();
            String Md5_AppId = DigestUtils.md5DigestAsHex(strAppId.getBytes());
            StringBuilder sb = new StringBuilder(Md5_AppId);
            String strAccess_token = sb.reverse().toString();

            map.put("appid", strAppId);
            map.put("access_token", strAccess_token);
            map.put("schoolId", taskInfo.getSchoolId());
            map.put("term", taskInfo.getTerm());
            map.put("courseNo", course.getBaseCourseId());
            map.put("testType", courseInput.getAssessmentId().toString());

            String url = lancooConfig.getBaseAddr().concat(path);
            String body = JSON.toJSONString(map);
            HttpRequest post = HttpUtil.createPost(url).body(body);
            HttpResponse execute = post.execute();
            BasicPlatformResponse basicPlatformResponse = JSONObject.parseObject(execute.body(), BasicPlatformResponse.class);
            if (!basicPlatformResponse.getStatusCode().equals(200)) {
                throw new BizException("同步基础教务考核方式失败！");
            }
        }
        //更新教学班课程参数
//        teachingClassService.lambdaUpdate()
//                .eq(TeachingClass::getCourseId, courseInput.getCourseId())
//                .set(courseInput.getAssessmentId() != null, TeachingClass::getAssessmentId, courseInput.getAssessmentId())
//                .set(StrUtil.isNotEmpty(courseInput.getAssessmentName()), TeachingClass::getAssessmentName, courseInput.getAssessmentName())
//                .update();
        return true;
    }


    @Override
    public List<CourseTreeVo> getCourseTree(Integer taskId, String baseCollegeId, String keyword) {
        List<CourseTreeVo> list = new ArrayList<>();
        List<CourseDto> courseList = courseMapper.getCourseDto(taskId, baseCollegeId, keyword);
        //课程根据学院分组
        Map<String, List<CourseDto>> courseGroupByCollege = courseList.stream().collect(Collectors.groupingBy(CourseDto::getBaseCollegeId));
        courseGroupByCollege.forEach((collegeId, course) -> {
            CourseTreeVo courseTreeVo = new CourseTreeVo();
            courseTreeVo.setBaseCourseId(collegeId);
            courseTreeVo.setCourseName(course.get(0).getCollegeName());

            for (CourseDto courseDto : course) {
                //环节
                if (courseDto.getFlag() == 2) {
                    courseTreeVo.getSegment().add(courseDto);
                } else {
                    if (courseDto.getIsSelect() == 0) {
                        courseTreeVo.getNoRequireCourse().add(courseDto);
                    }
                    //课程同时属于预选和在线选课的话，归为预选课程
                    if (courseDto.getIsSelect() == 1 || courseDto.getIsSelect() == 3) {
                        courseTreeVo.getPreSelect().add(courseDto);
                    }
                    if (courseDto.getIsSelect() == 2) {
                        courseTreeVo.getOnlineSelect().add(courseDto);
                    }
                }
            }
            list.add(courseTreeVo);
        });

//        //过滤没有课程参数的课程
//        List<Long> courseIds = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream().map(Course::getCourseId).collect(Collectors.toList());
        List<Long> courseIds = courseList.stream().map(CourseDto::getCourseId).collect(Collectors.toList());
        List<Long> removeIds = new ArrayList<>();
        List<CourseWeek> courseWeekList = courseWeekService.lambdaQuery().eq(CourseWeek::getTaskId, taskId).list();
        for (Long tempCourseId : courseIds) {
            List<CourseWeek> weeks = courseWeekList.stream().filter(a -> a.getCourseId().equals(tempCourseId)).collect(Collectors.toList());
            if (CollUtil.isEmpty(weeks)) {
                removeIds.add(tempCourseId);
            }
        }
        list.forEach(a -> {
            a.getNoRequireCourse().removeIf(p -> removeIds.contains(p.getCourseId()));
            a.getPreSelect().removeIf(p -> removeIds.contains(p.getCourseId()));
            a.getOnlineSelect().removeIf(p -> removeIds.contains(p.getCourseId()));
            a.getSegment().removeIf(p -> removeIds.contains(p.getCourseId()));
        });
        //过滤没有培养方案的课程
//        List<String> baseCourseIds = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream().map(Course::getBaseCourseId).collect(Collectors.toList());
        List<String> baseCourseIds = courseList.stream().map(CourseDto::getBaseCourseId).collect(Collectors.toList());
        List<String> removeBaseIds = new ArrayList<>();
        List<PlanTeaching> planTeachingList = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId).list();
        List<PlanTeachingCourse> planCourseList = planTeachingCourseService.lambdaQuery().eq(PlanTeachingCourse::getTaskId, taskId).list();
        for (String baseCourseId : baseCourseIds) {
            List<PlanTeachingCourse> planCourse = planCourseList.stream().filter(a -> a.getBaseCourseId().equals(baseCourseId)).collect(Collectors.toList());
            if (CollUtil.isEmpty(planCourse)) {
                removeBaseIds.add(baseCourseId);
            } else {
                //获取课程对应的培养方案
                List<String> planIds = planCourse.stream().map(PlanTeachingCourse::getBaseTeachingPlanId).collect(Collectors.toList());
                List<PlanTeaching> planTeachings = planTeachingList.stream().filter(a -> planIds.contains(a.getBaseTeachingPlanId())).collect(Collectors.toList());
                //没有任何一个培养方案启用的课程则将其过滤掉
                if (planTeachings.stream().noneMatch(a -> a.getIsEnable() == 1)) {
                    removeBaseIds.add(baseCourseId);
                }
            }
        }
        list.forEach(a -> {
            a.getNoRequireCourse().removeIf(p -> removeBaseIds.contains(p.getBaseCourseId()));
            a.getPreSelect().removeIf(p -> removeBaseIds.contains(p.getBaseCourseId()));
            a.getOnlineSelect().removeIf(p -> removeBaseIds.contains(p.getBaseCourseId()));
            a.getSegment().removeIf(p -> removeBaseIds.contains(p.getBaseCourseId()));
        });

        //检测学院教学班生成状态
        for (CourseTreeVo courseTreeVo : list) {
            boolean flag1 = courseTreeVo.getNoRequireCourse().stream().noneMatch(a -> a.getTeachingSet().equals(0));
            boolean flag2 = courseTreeVo.getOnlineSelect().stream().noneMatch(a -> a.getTeachingSet().equals(0));
            boolean flag3 = courseTreeVo.getPreSelect().stream().noneMatch(a -> a.getTeachingSet().equals(0));
            boolean flag4 = courseTreeVo.getSegment().stream().noneMatch(a -> a.getTeachingSet().equals(0));
            if (flag1 && flag2 && flag3 && flag4) {
                courseTreeVo.setTeachingSet(1);
            }
        }
        return list;
    }

    @Override
    public PageInfo<TeachingClass> getTeachingClassByCourse(Integer taskId, Long courseId, Integer currentPage, Integer pageSize, Integer teachingClassType, String keyword, Long teachingClassId) {
        Course course = courseService.getById(courseId);
        List<CourseWeek> courseWeeks = courseWeekService.lambdaQuery().eq(CourseWeek::getCourseId, courseId).list();
        List<TeachingClass> result = new ArrayList<>();
        List<Teacher> teacherList1 = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).list();
        //获取教学班
        List<TeachingClass> teachingClassList = teachingClassService.lambdaQuery()
                .eq(TeachingClass::getTaskId, taskId)
                .eq(TeachingClass::getCourseId, courseId)
                .eq(TeachingClass::getIsOptional, 0)
                .isNull(TeachingClass::getUniqueShiftSign)
                .eq(ObjUtil.isNotNull(teachingClassType), TeachingClass::getTeachingClassType, teachingClassType)
                .list();
        List<TeachingClassWeek> weekList = teachingClassWeekService.list();
        List<TeachingClassTeacher> teacherList = teachingClassTeacherService.list();
        List<TeachingClassStudent> studentList = teachingClassStudentService.lambdaQuery().eq(TeachingClassStudent::getFlag, 1).list();
        Integer number = 1;
        List<TeachingClass> addClass = new ArrayList<>();
        for (TeachingClass teachingClass : teachingClassList) {
            if (StringUtils.isNotBlank(teachingClass.getSplitTeacherUuid())) {
                List<TeachingClass> splitTeacherClassList = teachingClassList.stream().filter(a -> a.getSplitTeacherUuid() != null && a.getSplitTeacherUuid().equals(teachingClass.getSplitTeacherUuid())).collect(Collectors.toList());
                List<Long> splitClassIds = splitTeacherClassList.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
                TeachingClass view = new TeachingClass();
                BeanUtils.copyProperties(teachingClass, view);
                view.setTotalHour(course.getLectureHour() + course.getExperimentalHour() + course.getOtherHour() + course.getComputerHour());
                view.setClassNumTemp(view.getClassNum());
                if (teachingClass.getSuperPercent() != null) {
                    view.setClassNumTemp(view.getClassNum() + view.getClassNum() * view.getSuperPercent() / 100);
                }
                //获取教学班周数
                List<TeachingClassWeek> teachingClassWeek = weekList.stream()
                        .filter(a -> splitClassIds.contains(a.getTeachingClassId()))
                        .collect(Collectors.toList());
                for (TeachingClassWeek item : teachingClassWeek) {
                    switch (item.getHourType()) {
                        case 1:
                            item.setHourTypeName("讲授");
                            break;
                        case 2:
                            item.setHourTypeName("实验");
                            break;
                        case 3:
                            item.setHourTypeName("上机");
                            break;
                        case 4:
                            item.setHourTypeName("其他");
                            break;
                        default:
                            break;
                    }
                }
                view.setTeachingClassWeeks(teachingClassWeek);

                List<TeachingClassWeekListDto> teachingClassWeekListDtoList = new ArrayList<>();
                List<Integer> collect = teachingClassWeek.stream().map(TeachingClassWeek::getHourType).distinct().collect(Collectors.toList());
                for (Integer hourType : collect) {
                    TeachingClassWeekListDto weekListDto = new TeachingClassWeekListDto();
                    Optional<CourseWeek> optional = courseWeeks.stream().filter(a -> a.getHourType().equals(hourType)).findFirst();
                    if (optional.isPresent()) {
                        CourseWeek courseWeek = optional.get();
                        weekListDto.setTotalHour(courseWeek.getTotalHour());
                        List<TeachingClassWeek> teachingClassWeeks = teachingClassWeek.stream().filter(a -> a.getHourType().equals(hourType)).collect(Collectors.toList());
                        weekListDto.setTeachingClassWeeks(teachingClassWeeks);
                        weekListDto.setHourTypeName(teachingClassWeeks.get(0).getHourTypeName());
                        teachingClassWeekListDtoList.add(weekListDto);
                    }
                }
                view.setTeachingClassWeekList(teachingClassWeekListDtoList);

                //获取教学班老师
                List<TeachingClassTeacher> teachingClassTeacher = teacherList.stream()
                        .filter(a -> splitClassIds.contains(a.getTeachingClassId()))
                        .collect(Collectors.toList());
                for (TeachingClassTeacher item : teachingClassTeacher) {
                    Teacher teacher = teacherList1.stream().filter(a -> a.getTeacherId().equals(item.getTeacherId())).findFirst().get();
                    item.setIdentity(teacher.getIdentity())
                            .setImageUrl(teacher.getImageUrl())
                            .setTeacherName(teacher.getTeacherName())
                            .setBaseTeacherId(teacher.getBaseTeacherId());
                    switch (item.getHourType()) {
                        case 1:
                            item.setHourTypeName("讲授");
                            break;
                        case 2:
                            item.setHourTypeName("实验");
                            break;
                        case 3:
                            item.setHourTypeName("上机");
                            break;
                        case 4:
                            item.setHourTypeName("其他");
                            break;
                        default:
                            break;
                    }
                }
                view.setTeachingClassTeachers(teachingClassTeacher);
                //教学班学生
                List<TeachingClassStudent> teachingClassStudent = studentList.stream()
                        .filter(a -> splitClassIds.contains(a.getTeachingClassId()))
                        .collect(Collectors.toList());
                List<Long> studentIds = teachingClassStudent.stream().map(TeachingClassStudent::getStudentId).distinct().collect(Collectors.toList());
                view.setStudentIds(studentIds);
                addClass.add(view);
            } else {
                TeachingClass view = new TeachingClass();
                BeanUtils.copyProperties(teachingClass, view);
                view.setTotalHour(course.getLectureHour() + course.getExperimentalHour() + course.getOtherHour() + course.getComputerHour());
                view.setClassNumTemp(view.getClassNum());
                if (teachingClass.getSuperPercent() != null) {
                    view.setClassNumTemp(view.getClassNum() + view.getClassNum() * view.getSuperPercent() / 100);
                }
                //获取教学班周数
                List<TeachingClassWeek> teachingClassWeek = weekList.stream()
                        .filter(a -> a.getTeachingClassId().equals(teachingClass.getTeachingClassId()))
                        .collect(Collectors.toList());
                for (TeachingClassWeek item : teachingClassWeek) {
                    switch (item.getHourType()) {
                        case 1:
                            item.setHourTypeName("讲授");
                            break;
                        case 2:
                            item.setHourTypeName("实验");
                            break;
                        case 3:
                            item.setHourTypeName("上机");
                            break;
                        case 4:
                            item.setHourTypeName("其他");
                            break;
                        default:
                            break;
                    }
                }
                view.setTeachingClassWeeks(teachingClassWeek);

                List<TeachingClassWeekListDto> teachingClassWeekListDtoList = new ArrayList<>();
                List<Integer> collect = teachingClassWeek.stream().map(TeachingClassWeek::getHourType).distinct().collect(Collectors.toList());
                for (Integer hourType : collect) {
                    TeachingClassWeekListDto weekListDto = new TeachingClassWeekListDto();
                    Optional<CourseWeek> optional = courseWeeks.stream().filter(a -> a.getHourType().equals(hourType)).findFirst();
                    if (optional.isPresent()) {
                        CourseWeek courseWeek = optional.get();
                        weekListDto.setTotalHour(courseWeek.getTotalHour());
                        List<TeachingClassWeek> teachingClassWeeks = teachingClassWeek.stream().filter(a -> a.getHourType().equals(hourType)).collect(Collectors.toList());
                        weekListDto.setTeachingClassWeeks(teachingClassWeeks);
                        weekListDto.setHourTypeName(teachingClassWeeks.get(0).getHourTypeName());
                        teachingClassWeekListDtoList.add(weekListDto);
                    }
                }
                view.setTeachingClassWeekList(teachingClassWeekListDtoList);

                //获取教学班老师
                List<TeachingClassTeacher> teachingClassTeacher = teacherList.stream()
                        .filter(a -> a.getTeachingClassId().equals(teachingClass.getTeachingClassId()))
                        .collect(Collectors.toList());
                for (TeachingClassTeacher item : teachingClassTeacher) {
                    Teacher teacher = teacherList1.stream().filter(a -> a.getTeacherId().equals(item.getTeacherId())).findFirst().get();
                    item.setIdentity(teacher.getIdentity())
                            .setImageUrl(teacher.getImageUrl())
                            .setTeacherName(teacher.getTeacherName())
                            .setBaseTeacherId(teacher.getBaseTeacherId());
                    switch (item.getHourType()) {
                        case 1:
                            item.setHourTypeName("讲授");
                            break;
                        case 2:
                            item.setHourTypeName("实验");
                            break;
                        case 3:
                            item.setHourTypeName("上机");
                            break;
                        case 4:
                            item.setHourTypeName("其他");
                            break;
                        default:
                            break;
                    }
                }
                view.setTeachingClassTeachers(teachingClassTeacher);
                //教学班学生
                List<TeachingClassStudent> teachingClassStudent = studentList.stream()
                        .filter(a -> a.getTeachingClassId().equals(teachingClass.getTeachingClassId()))
                        .collect(Collectors.toList());
                List<Long> studentIds = teachingClassStudent.stream().map(TeachingClassStudent::getStudentId).distinct().collect(Collectors.toList());
                view.setStudentIds(studentIds);
                result.add(view);
            }
        }
        List<String> uuids = addClass.stream().map(TeachingClass::getSplitTeacherUuid).distinct().collect(Collectors.toList());
        for (String uuid : uuids) {
            TeachingClass view = addClass.stream().filter(a -> a.getSplitTeacherUuid().equals(uuid)).collect(Collectors.toList()).get(0);
            result.add(view);
        }
        if (StrUtil.isNotEmpty(keyword)){
            result = result.stream().filter(o -> o.getTeachingClassName().contains(keyword)).collect(Collectors.toList());
        }
        if (teachingClassId != null){
            result = result.stream().filter(o ->
                    o.getTeachingClassWeeks().stream().anyMatch(w ->
                            w.getTeachingClassId().equals(teachingClassId)))
                    .collect(Collectors.toList());
        }
        return PagingUtil.getPages(currentPage, pageSize, result);
    }


    @Override
    public SetCourseDto<PlanTeaching> getPlanByCourse(Integer taskId, Long courseId, Integer campusId, Integer studyNature, String baseCollegeId, Integer flag) {
        SetCourseDto<PlanTeaching> result = new SetCourseDto<>();
        List<PlanTeaching> data = new ArrayList<>();
        Course course = courseMapper.selectById(courseId);
        //专业年级
        List<MajorGrade> majorGradeList = majorGradeService.lambdaQuery().eq(MajorGrade::getTaskId, taskId).list();
        //学生
        List<Student> studentList = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();
        //已选学生
        List<TeachingClassStudent> teachingClassStudents = teachingClassStudentService.lambdaQuery().eq(TeachingClassStudent::getFlag, 1).list();
        //培养方案-课程对应表
        List<PlanTeachingCourse> planCourse = planTeachingCourseService.lambdaQuery()
                .eq(PlanTeachingCourse::getTaskId, taskId)
                .eq(PlanTeachingCourse::getBaseCourseId, course.getBaseCourseId()).list();
        List<String> planIds = planCourse.stream().map(PlanTeachingCourse::getBaseTeachingPlanId).collect(Collectors.toList());
        List<PlanTeachingStudent> planTeachingStudentList = planTeachingStudentService.lambdaQuery()
                .eq(PlanTeachingStudent::getTaskId, taskId)
                .in(CollUtil.isNotEmpty(planIds),PlanTeachingStudent::getBaseTeachingPlanId,planIds)
                .list();
        //培养方案
        List<PlanTeaching> planTeachingList = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId).list();
        if (CollUtil.isNotEmpty(planCourse)) {
            for (PlanTeachingCourse item : planCourse) {
                Optional<PlanTeaching> optional = planTeachingList.stream().filter(a -> a.getBaseTeachingPlanId().equals(item.getBaseTeachingPlanId())).findFirst();
                if (optional.isPresent()) {
                    PlanTeaching view = optional.get();
                    //名称
                    view.setTeachingPlanName(view.getGradeName() + view.getMajorName() + view.getMajorVersionName());
                    Optional<MajorGrade> optional1 = majorGradeList.stream().filter(a -> a.getGradeId().equals(view.getGradeId()) && a.getBaseMajorId().equals(view.getBaseMajorId())).findFirst();
                    if (optional1.isPresent()) {
                        //所属校区
                        view.setCampusName(optional1.get().getCampusName());
                        view.setCampusId(optional1.get().getCampusId());
                    }
                    //填充学生
                    if (flag == 1) {
                        //选课人数
                        List<CssPreSelectStudent> preSelectStudents = cssPreSelectStudentService.lambdaQuery().eq(CssPreSelectStudent::getCourseId, courseId).list();
                        List<Long> studentIds = preSelectStudents.stream().map(CssPreSelectStudent::getStudentId).collect(Collectors.toList());
                        view.setStudentIds(CollUtil.isNotEmpty(studentIds) ? studentIds : new ArrayList<>());
                        view.setCourseName(course.getCourseName());
                    } else {
                        //修读人数
                        List<String> baseIdCollect = planTeachingStudentList.stream().filter(a -> a.getBaseTeachingPlanId().equals(item.getBaseTeachingPlanId())).collect(Collectors.toList())
                                .stream().map(PlanTeachingStudent::getBaseStudentId).collect(Collectors.toList());
                        List<Long> studentIds = studentList.stream().filter(a -> baseIdCollect.contains(a.getBaseStudentId())).map(Student::getStudentId).collect(Collectors.toList());
                        //已选人数
                        List<Long> removeIds = new ArrayList<>();
                        for (Long studentId : studentIds) {
                            if (teachingClassStudents.stream().anyMatch(a -> a.getStudentId().equals(studentId) && a.getCourseId().equals(courseId))) {
                                removeIds.add(studentId);
                            }
                        }
                        if (CollUtil.isNotEmpty(removeIds)) {
                            studentIds.removeAll(removeIds);
                        }
                        view.setStudentIds(studentIds);
                    }
                    data.add(view);
                }
            }
        }
        if (flag == 1) {
            //获取所有预选课学生
            List<CssPreSelectStudent> preSelectStudents = cssPreSelectStudentService.lambdaQuery().eq(CssPreSelectStudent::getCourseId, courseId).list();
            //获取所有预选课学生id
            List<Long> studentIds = preSelectStudents.stream().map(CssPreSelectStudent::getStudentId).collect(Collectors.toList());
            //预选课学生id转换成基础id
            List<String> baseStuIds = studentList.stream().filter(a -> studentIds.contains(a.getStudentId())).map(Student::getBaseStudentId).collect(Collectors.toList());
            List<PlanTeachingStudent> planTeachingStudents = planTeachingStudentService.lambdaQuery().eq(PlanTeachingStudent::getTaskId, taskId).list();
            List<PlanTeaching> preData = new ArrayList<>();
            //预选课数据处理（根据校区和主修辅修分类）
            List<Integer> campusIds = data.stream().map(PlanTeaching::getCampusId).distinct().collect(Collectors.toList());
            List<Integer> studyNatures = data.stream().map(PlanTeaching::getStudyNature).distinct().collect(Collectors.toList());
            for (Integer tempCampusId : campusIds) {
                for (Integer tempStudyNature : studyNatures) {
                    PlanTeaching view = new PlanTeaching();
                    String campusName = data.stream().filter(a -> a.getCampusId().equals(tempCampusId)).findFirst().get().getCampusName();
                    view.setCampusId(tempCampusId);
                    view.setCampusName(campusName);
                    view.setStudyNature(tempStudyNature);
                    //该校区主修的培养计划基础id
                    List<String> basePlanIds = data.stream()
                            .filter(a -> a.getStudyNature().equals(tempStudyNature) && a.getCampusId().equals(tempCampusId))
                            .map(PlanTeaching::getBaseTeachingPlanId)
                            .collect(Collectors.toList());
                    //获取属于该分类且已选课的基础学生id
                    List<String> needBaseStuIds = planTeachingStudents.stream()
                            .filter(a -> baseStuIds.contains(a.getBaseStudentId()) && basePlanIds.contains(a.getBaseTeachingPlanId()))
                            .map(PlanTeachingStudent::getBaseStudentId)
                            .collect(Collectors.toList());
                    List<Long> needStuIds = studentList.stream().filter(a -> needBaseStuIds.contains(a.getBaseStudentId())).map(Student::getStudentId).collect(Collectors.toList());
                    view.setStudentIds(needStuIds);
                    preData.add(view);
                }
            }
            data = preData;
        }
        if (campusId != null) {
            data = data.stream().filter(a -> a.getCampusId().equals(campusId)).collect(Collectors.toList());
        }
        if (studyNature != null) {
            data = data.stream().filter(a -> a.getStudyNature().equals(studyNature)).collect(Collectors.toList());
        }
        //过滤没有修读人数的教学班
        if (flag != 1) {
            data = data.stream().filter(a -> a.getStudentIds().size() != 0).collect(Collectors.toList());
        }
        result.setTotalSetNum(data.size());
        result.setList(data);
        return result;
    }


    @Override
    public String autoMatchTeacher(Integer taskId, Long courseId) {
        List<TeachingClassTeacher> teachingClassTeacherList = new ArrayList<>();
        List<Teacher> teachers = new ArrayList<>();
        List<TeachingClass> teachingClasses = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).eq(TeachingClass::getCourseId, courseId).list();
        List<Long> teachingClassIds = teachingClasses.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
        List<TeachingClassWeek> teachingClassWeeks = teachingClassWeekService.lambdaQuery().in(TeachingClassWeek::getTeachingClassId, teachingClassIds).list();
        List<TeachingClassTeacher> teachingClassTeachers = teachingClassTeacherService.lambdaQuery().in(TeachingClassTeacher::getTeachingClassId, teachingClassIds).list();
        //获取已分配的教学班id
        List<Long> finishIds = teachingClassTeachers.stream().map(TeachingClassTeacher::getTeachingClassId).collect(Collectors.toList());
        //获取未分配的教学班id
        List<Long> needIds = teachingClassIds;
        needIds.removeAll(finishIds);
        if (CollUtil.isNotEmpty(needIds)) {
            //获取需要分配的教学班
            List<TeachingClass> needTeachingClassList = teachingClassService.lambdaQuery().in(TeachingClass::getTeachingClassId, needIds).list();
            List<Long> ids = needTeachingClassList.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
            List<TeachingClassWeek> classWeeks = teachingClassWeekService.lambdaQuery().in(TeachingClassWeek::getTeachingClassId, ids).list();
            //获取可以分配的教师
            List<TeacherCourse> teacherCourses = teacherCourseService.lambdaQuery().eq(TeacherCourse::getCourseId, courseId).list();
            List<Long> teacherIds = teacherCourses.stream().map(TeacherCourse::getTeacherId).collect(Collectors.toList());
            if (teacherIds.size() == 0) {
                throw new BizException("当前系统未检测到该课程的任课教师信息，建议到基础信息->教师信息设置模块，设置教师的任课信息，再进行自动分配");
            }
            List<Teacher> teacherList = teacherService.lambdaQuery().in(Teacher::getTeacherId, teacherIds).eq(Teacher::getIdentity, 1).list();
            if (teacherList.size() == 0) {
                throw new BizException("当前系统未检测到该课程的任课教师信息，建议到基础信息->教师信息设置模块，设置教师的任课信息，再进行自动分配");
            }
            //设置任课老师
            if (classWeeks.size() > teacherList.size()) {
                int teacherNum = teacherList.size();
                AtomicInteger number = new AtomicInteger();
                needTeachingClassList.forEach(o -> {
                    List<TeachingClassWeek> weeks = teachingClassWeeks.stream().filter(p -> p.getTeachingClassId().equals(o.getTeachingClassId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(weeks)) {
                        weeks.forEach(tw -> {
                            Teacher teacher = teacherList.get(number.get() % teacherNum);
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(o.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacher.getTeacherId());
                            teachingClassTeacher.setTeacherName(teacher.getTeacherName());
                            teachingClassTeacher.setHourType(tw.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                            number.getAndIncrement();
                        });
                    }
                });
            } else {
                //如果教师数量大于班级数量
                AtomicInteger nums = new AtomicInteger();
                needTeachingClassList.forEach(o -> {
                    List<TeachingClassWeek> weeks = teachingClassWeeks.stream().filter(p -> p.getTeachingClassId().equals(o.getTeachingClassId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(weeks)) {
                        weeks.forEach(tw -> {
                            Teacher teacher = teacherList.get(nums.get());
                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(o.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacher.getTeacherId());
                            teachingClassTeacher.setTeacherName(teacher.getTeacherName());
                            teachingClassTeacher.setHourType(tw.getHourType());
                            teachingClassTeacherList.add(teachingClassTeacher);
                            nums.getAndIncrement();
                        });
                    }
                });
            }
        }
        teachingClassTeacherService.saveOrUpdateBatch(teachingClassTeacherList);
        return "成功";
    }


    @Override
    public CourseParameterSetVo getCourseParameterSetVo(Integer taskId) {
        return courseMapper.getCourseParameterSet(taskId);
    }

//    @Override
//    public List<CourseTreeVo> getCourseTree(Integer taskId, String baseCollegeId, String keyword) {
//        List<CourseTreeVo> list = new ArrayList<>();
//        List<CourseDto> courseList = courseMapper.getCourseDto(taskId, baseCollegeId, keyword);
//        //课程根据学院分组
//        Map<String, List<CourseDto>> courseGroupByCollege = courseList.stream().collect(Collectors.groupingBy(CourseDto::getBaseCollegeId));
//        courseGroupByCollege.forEach((collegeId, course) -> {
//            CourseTreeVo courseTreeVo = new CourseTreeVo();
//            courseTreeVo.setBaseCourseId(collegeId);
//            courseTreeVo.setCourseName(course.get(0).getCollegeName());
//
//            for (CourseDto courseDto : course) {
//                //环节
//                if (courseDto.getFlag() == 2) {
//                    courseTreeVo.getSegment().add(courseDto);
//                } else {
//                    if (courseDto.getIsSelect() == 0) {
//                        courseTreeVo.getNoRequireCourse().add(courseDto);
//                    }
//                    //课程属于预选和在线选课的话，归为预选课程
//                    if (courseDto.getIsSelect() == 1 || courseDto.getIsSelect() == 3) {
//                        courseTreeVo.getPreSelect().add(courseDto);
//                    }
//                    if (courseDto.getIsSelect() == 2) {
//                        courseTreeVo.getOnlineSelect().add(courseDto);
//                    }
//                }
//            }
//            list.add(courseTreeVo);
//        });
//        return list;
//    }


    @Override
    public List<Course> getCourseType(Integer taskId, String baseCollegeId) {
        return baseMapper.getCourseType(taskId, baseCollegeId);
    }

    @Override
    public List<Integer> getCourseNature(Integer taskId, String baseCollegeId, String courseTypeId) {
        return baseMapper.getCourseNature(taskId, baseCollegeId, courseTypeId);
    }


    @Override
    public void exportCourseInformation(HttpServletResponse response, Integer taskId, String courseName, String collegeName, String courseName1, String courseType, String courseNatureName, String selectStudentNums, String state, String isCourseState, String baseCollegeId, String courseTypeId, Optional<Integer> courseNature, String keyword, Optional<Integer> isEnable, Optional<Integer> isAchieveOpen, Integer pageSize, Integer currentPage) {


        List<ExcelPreSelectCourseLog> excelPreSelectCourseLogs = new ArrayList<>();
//        ResultDto<PreLogsDto> preLogs = selectCourseService.getPreLogs(baseCollegeId, gradeId, classId, courseId, startDateTime, endDateTime, keyword, -1, 1, taskId);


//        preLogs.getList().forEach(o -> {
//            ExcelPreSelectCourseLog excelPreSelectCourseLog = new ExcelPreSelectCourseLog();
//            excelPreSelectCourseLog.setOption(o.getFlag() == 1 ? "已选" : (o.getFlag() == 2 ? "退选" : "管理员移除"));
//
//            excelPreSelectCourseLogs.add(excelPreSelectCourseLog);
//
//        });

//        TaskInfo taskInfo = taskInfoService.getById(taskId);


        TaskInfo taskInfo = new TaskInfo();
        //构建标题
        String title = " {} {}预选课信息日志导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");


        MyExcelUtils.exportExcel(excelPreSelectCourseLogs,
                format,
                "课程信息导出",
                ExcelPreSelectCourseLog.class,
                "课程信息导出" + time + ".xls", response);
    }


    @Override
    public void importCourseInformation(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {


//        List<ExcelTeacherInformationSettings> excelTeachingActivities = this.readTeacherInformationSettings(file);
//
//        if (flag == 2) {
//            this.lambdaUpdate().eq(Teacher::getIdentity, null).set(Teacher::getCampusId, null)
//                    .eq(Teacher::getCampusName, null).set(Teacher::getIsCampusCross, 0).update();
//            teacherCourseService.lambdaUpdate().eq(TeacherCourse::getTaskId, taskId).remove();
//        }
//
//
//        List<Teacher> teachers = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getTaskId, taskId));
//
//        Map<String, Campus> campusMap = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list().stream().collect(Collectors.toMap(Campus::getCampusName, Function.identity(), (o1, o2) -> o1));
//
//
//        Map<String, College> collegeMap = collegeService.lambdaQuery().eq(College::getTaskId, taskId).list().stream()
//                .collect(Collectors.toMap(College::getCollegeName, Function.identity(), (o1, o2) -> o1));
//
//
//        Map<String, Teacher> teacherMap = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getTaskId, taskId))
//                .stream().collect(Collectors.toMap(Teacher::getBaseTeacherId, Function.identity(), (o1, o2) -> o1));
//
//        Map<String, Course> courseMap = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream()
//                .collect(Collectors.toMap(Course::getCourseName, Function.identity(), (o1, o2) -> o1));
//
//
//        Long index = 3L;
//        for (ExcelTeacherInformationSettings excelTeachingActivity : excelTeachingActivities) {
//            excelTeachingActivity.setId(index);
//            index++;
//        }
//
//
//        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
//        for (ExcelTeacherInformationSettings excelTeachingActivity : excelTeachingActivities) {
//
//            if (!StringUtils.isBlank(excelTeachingActivity.getBaseTeacherId()) || !teacherMap.containsKey(excelTeachingActivity.getBaseTeacherId())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getBaseTeacherId() + "工号教师不存在");
//                errorExcelVos.add(errorExcelVo);
//            }
//
//
//            if (!StringUtils.isBlank(excelTeachingActivity.getCourseName())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getCourseName() + "课程未设置");
//                errorExcelVos.add(errorExcelVo);
//            } else {
//                List<String> courseIds = new ArrayList<>(Arrays.asList(excelTeachingActivity.getCourseName().split(",")));
//
//                courseIds.forEach(o -> {
//                    if (!StringUtils.isBlank(o) || !courseMap.containsKey(o)) {
//                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                        errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                        errorExcelVo.setErrorMsg(o + "课程不存在");
//                        errorExcelVos.add(errorExcelVo);
//                    }
//                });
//            }
//
//
//            if (!StringUtils.isBlank(excelTeachingActivity.getIdentity())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getId() + "行教师身份未设置");
//                errorExcelVos.add(errorExcelVo);
//            }
//
//
//            if (!StringUtils.isBlank(excelTeachingActivity.getCampusName()) || !campusMap.containsKey(excelTeachingActivity.getCampusName())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getCampusName() + "校区不存在");
//                errorExcelVos.add(errorExcelVo);
//            }
//
//
//            if (!StringUtils.isBlank(excelTeachingActivity.getCollegeName()) || !collegeMap.containsKey(excelTeachingActivity.getCollegeName())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getCollegeName() + "院系不存在");
//                errorExcelVos.add(errorExcelVo);
//            }
//        }
//
//
//        Integer errorExcelVos1 = errorExcelVos.size();
//        if (CollUtil.isNotEmpty(errorExcelVos)) {
//            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
//
//            MyExcelUtils.exportExcel(errorExcelVos,
//                    "导入场地分配信息错误",
//                    "错误信息",
//                    ErrorExcelVo.class,
//                    "导入错误信息" + time + ".xls", response);
//            throw new BizException("导入场地分配信息错误");
//        }
//
//        if (errorExcelVos1 == 0) {
//            List<ErrorExcelVo> errorExcelVos2 = new ArrayList<>();
//
//
//            List<Teacher> teacherList1 = new ArrayList<>();
//
//
//            List<TeacherCourse> teacherCourses = new ArrayList<>();
//
//            for (ExcelTeacherInformationSettings excelTeachingActivity : excelTeachingActivities) {
//
//
//                List<Teacher> teacherList = teachers.stream().filter(p -> p.getBaseTeacherId().equals(excelTeachingActivity.getBaseTeacherId())).collect(Collectors.toList());
//
//
//                if (CollUtil.isNotEmpty(teacherList)) {
//                    teacherList.forEach(o -> {
//                        o.setCampusId(campusMap.get(excelTeachingActivity.getCampusName()).getCampusId());
//                        o.setCampusName(campusMap.get(excelTeachingActivity.getCampusName()).getCampusName());
//                        o.setIsCampusCross("已开启".equals(excelTeachingActivity.getIsEnable()) ? 1 : 0);
//                        teacherList1.add(o);
//
//                        List<String> coursNames = new ArrayList<>(Arrays.asList(excelTeachingActivity.getCourseName().split(",")));
//
//                        coursNames.forEach(c -> {
//                            Course course = courseMap.get(c);
//                            TeacherCourse teacherCourse = new TeacherCourse();
//                            teacherCourse.setTaskId(taskId);
//                            teacherCourse.setTeacherId(o.getTeacherId());
//                            teacherCourse.setCourseId(course.getCourseId());
//                            teacherCourse.setCourseName(course.getCourseName());
//                            teacherCourse.setFlag(course.getFlag());
//                            teacherCourses.add(teacherCourse);
//
//                        });
//                    });
//
//
//                } else {
//                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                    errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                    errorExcelVo.setErrorMsg(excelTeachingActivity.getCampusName() + excelTeachingActivity.getCollegeName() + "不存在");
//                    errorExcelVos2.add(errorExcelVo);
//                }
//
//
//            }
//
//            Integer errorExcelVos3 = errorExcelVos2.size();
//
//            if (CollUtil.isNotEmpty(errorExcelVos2)) {
//                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
//                response.setCharacterEncoding("UTF-8");
//                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
//
//                MyExcelUtils.exportExcel(errorExcelVos2,
//                        "导入教学活动信息错误",
//                        "错误信息",
//                        ErrorExcelVo.class,
//                        "导入错误信息" + time + ".xls", response);
//                throw new BizException("导入教学活动信息错误");
//            }
//
//            if (errorExcelVos3 == 0) {
//                if (CollUtil.isNotEmpty(teacherList1)) {
//                    this.saveOrUpdateBatch(teacherList1);
//                }
//
//                if (CollUtil.isNotEmpty(teacherCourses)) {
//                    teacherCourseService.saveOrUpdateBatch(teacherCourses);
//                }
//            }
//        }
    }

    @Override
    public List<Course> getCourseLimit(Integer taskId) {
        return baseMapper.getCourseLimit(taskId);
    }

    @Override
    public void copyCourseLimit(Integer taskId, List<Course> courses) {
        baseMapper.copyCourseLimit(taskId, courses);
    }


}
